import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_model/cartoon_media_info.dart';
import 'package:tiktokadult/hj_model/home/module_detail_model.dart';
import 'package:tiktokadult/hj_page/cartoon_business/acg_widget_item.dart';
import 'package:tiktokadult/hj_page/cartoon_business/cartoon_sectionlist_page.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/routers/jump_router.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';
import 'package:tiktokadult/tools_base/widget/net_image_widget.dart';

import 'cartoon_sub_section_logic.dart';

final CarttonSectionTypes = {
  0: OneLargeAndFourSmall(), //一大四小
  1: EightGridV(), //八竖
  2: ThreeV(), //三竖屏
  3: FourGridH(), //四宫格
  4: EightGridH(), //八横
  5: SixteenV(), //16竖屏 pk样式
  7: TwoH(), //动漫二横屏
  8: FourGridV(), //四宫格横屏
  9: SixGridH(), //六宫格竖
  10: NineGrid(), //九宫格
  11: TwoVH(), //小列表
};

//设计成单例模式, 防止多次创建
abstract class CartoonSectionBaseType {
  Widget renderType(AllSection element, CartoonSubSectionLogic logic);

  //头部
  _buildSectionHeader(AllSection section) {
    return Padding(
        padding: const EdgeInsets.fromLTRB(16, 18, 16, 12),
        child: InkWell(
          onTap: () => Get.to(
            () => CartoonSectionListPage(
              sectionID: section.sectionID,
              tagName: section.sectionName,
            ),
          ),
          child: Row(
            children: [
              Text(
                section.sectionName ?? '',
                style: TextStyle(
                  fontSize: 18.sp,
                  color: Colors.white.withOpacity(0.9),
                  fontWeight: FontWeight.w600,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              Spacer(),
              Text(
                '更多',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Color(0xff989898),
                  fontWeight: FontWeight.w400,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              2.sizeBoxW,
              Icon(
                Icons.navigate_next,
                size: 18,
                color: Colors.white.withOpacity(.4),
              )
            ],
          ),
        ));
  }
}

//0 一大四小(横)
class OneLargeAndFourSmall extends CartoonSectionBaseType {
  static OneLargeAndFourSmall? _instance;
  OneLargeAndFourSmall._internal();
  //工厂构造函数
  factory OneLargeAndFourSmall() {
    if (_instance == null) {
      _instance = OneLargeAndFourSmall._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    List<CartoonMediaInfo> allMediaInfo = section.allMediaInfo ?? [];
    if (allMediaInfo.length >= 1) {
      CartoonMediaInfo info = allMediaInfo.first;
      return SliverToBoxAdapter(
        child: Column(
          children: [
            _buildSectionHeader(section),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 10),
              child: AspectRatio(
                aspectRatio: 343 / 238,
                child: AcgItemWidget(info: info, coverV: false),
              ),
            ),
            10.sizeBoxH,
            if (allMediaInfo.length > 1) ...[
              GridView.builder(
                padding: EdgeInsets.symmetric(horizontal: 10),
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 7,
                  mainAxisSpacing: 10,
                  childAspectRatio: 168 / 138,
                ),
                itemCount: min(allMediaInfo.sublist(1).length, 4),
                itemBuilder: (context, index) {
                  CartoonMediaInfo? meidiaInfo = section.allMediaInfo?[index + 1];
                  return AcgItemWidget(info: meidiaInfo, coverV: false);
                },
              ),
            ],
            0.5.sizeBoxH,
          ],
        ),
      );
    } else {
      return SliverToBoxAdapter(child: SizedBox.shrink());
    }
  }
}

// 1 四宫格(竖)
class FourGridV extends CartoonSectionBaseType {
  static FourGridV? _instance;
  FourGridV._internal();
  //工厂构造函数
  factory FourGridV() {
    if (_instance == null) {
      _instance = FourGridV._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    return SliverMainAxisGroup(
      slivers: [
        SliverToBoxAdapter(
          child: _buildSectionHeader(section),
        ),
        SliverPadding(
          padding: const EdgeInsets.only(left: 16, right: 16, bottom: 12),
          sliver: SliverGrid(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 12,
              crossAxisSpacing: 7,
              childAspectRatio: 168 / 266,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                CartoonMediaInfo? meidiaInfo = section.allMediaInfo?[index];
                return AcgItemWidget(info: meidiaInfo, coverV: true);
              },
              childCount: section.allMediaInfo?.length ?? 0,
            ),
          ),
        ),
      ],
    );
  }
}

// 1 四宫格(竖)
class FourGridH extends CartoonSectionBaseType {
  static FourGridH? _instance;
  FourGridH._internal();
  //工厂构造函数
  factory FourGridH() {
    if (_instance == null) {
      _instance = FourGridH._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    return SliverMainAxisGroup(
      slivers: [
        SliverToBoxAdapter(
          child: _buildSectionHeader(section),
        ),
        SliverPadding(
          padding: const EdgeInsets.only(left: 16, right: 16, bottom: 12),
          sliver: SliverGrid(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 12,
              crossAxisSpacing: 7,
              childAspectRatio: 168 / 154,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                CartoonMediaInfo? meidiaInfo = section.allMediaInfo?[index];
                return AcgItemWidget(info: meidiaInfo, coverV: false);
              },
              childCount: section.allMediaInfo?.length ?? 0,
            ),
          ),
        ),
      ],
    );
  }
}

//2 六宫格横
class SixGridH extends CartoonSectionBaseType {
  static SixGridH? _instance;
  SixGridH._internal();
  //工厂构造函数
  factory SixGridH() {
    if (_instance == null) {
      _instance = SixGridH._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    return SliverMainAxisGroup(slivers: [
      SliverToBoxAdapter(
        child: _buildSectionHeader(section),
      ),
      SliverPadding(
        padding: const EdgeInsets.only(left: 16, right: 16, bottom: 12),
        sliver: SliverGrid(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            mainAxisSpacing: 12,
            crossAxisSpacing: 5,
            childAspectRatio: 111 / 190,
          ),
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              CartoonMediaInfo? meidiaInfo = section.allMediaInfo?[index];
              return AcgItemWidget(info: meidiaInfo);
            },
            childCount: section.allMediaInfo?.length ?? 0,
          ),
        ),
      ),
    ]);
  }
}

//3 8竖
class EightGridV extends CartoonSectionBaseType {
  static EightGridV? _instance;
  double height = (Get.width - 30) / 2.5 * 216 / 133;
  EightGridV._internal();
  //工厂构造函数
  factory EightGridV() {
    if (_instance == null) {
      _instance = EightGridV._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    return SliverToBoxAdapter(
        child: Column(
      children: [
        _buildSectionHeader(section),
        SizedBox(
          height: height,
          child: GridView.builder(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 1,
              mainAxisSpacing: 7,
              crossAxisSpacing: 10,
              childAspectRatio: 216 / 133,
            ),
            itemCount: section.allMediaInfo?.length ?? 0,
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 10),
            itemBuilder: (context, index) {
              CartoonMediaInfo? meidiaInfo = section.allMediaInfo?[index];
              return AcgItemWidget(info: meidiaInfo);
            },
          ),
        ),
        6.sizeBoxH,
      ],
    ));
  }
}

//4 8横
class EightGridH extends CartoonSectionBaseType {
  static EightGridH? _instance;
  double height = (Get.width - 30) / 3.5 * 152 / 128;

  EightGridH._internal();
  //工厂构造函数
  factory EightGridH() {
    if (_instance == null) {
      _instance = EightGridH._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    return SliverToBoxAdapter(
      child: Column(
        children: [
          _buildSectionHeader(section),
          SizedBox(
            height: height,
            child: GridView.builder(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 1,
                mainAxisSpacing: 7,
                childAspectRatio: 128 / 152,
              ),
              itemCount: section.allMediaInfo?.length ?? 0,
              scrollDirection: Axis.horizontal,
              itemBuilder: (context, index) {
                CartoonMediaInfo? meidiaInfo = section.allMediaInfo?[index];
                return AcgItemWidget(info: meidiaInfo, coverV: false);
              },
            ),
          ),
          6.sizeBoxH,
        ],
      ),
    );
  }
}

//5 pk样式
class SixteenV extends CartoonSectionBaseType {
  static SixteenV? _instance;
  double height = (Get.width - 30) / 3.5 * 152 / 128;
  double width = Get.width - 42;

  SixteenV._internal();
  //工厂构造函数
  factory SixteenV() {
    if (_instance == null) {
      _instance = SixteenV._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    return SliverToBoxAdapter(
      child: Column(
        children: [
          _buildSectionHeader(section),
          SizedBox(
            height: (Get.width - 30 / 2.5) * 133 / 216.0 * 2 + 10,
            child: GridView.builder(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: 7,
                crossAxisSpacing: 10,
                childAspectRatio: 216 / 133,
              ),
              itemCount: section.allMediaInfo?.length ?? 0,
              scrollDirection: Axis.horizontal,
              itemBuilder: (context, index) {
                final value = handelPkSource(section.allMediaInfo ?? []);
                CartoonMediaInfo meidiaInfo = value[index];
                return AcgItemWidget(info: meidiaInfo);
              },
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 16, right: 16, top: 12),
            child: Column(
              children: [
                GetBuilder<CartoonSubSectionLogic>(
                  init: logic,
                  id: 'vote',
                  builder: (controller) => Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _buildPkText('${section.disVoteCount}'),
                      _buildPkText('${section.voteCount}'),
                    ],
                  ),
                ),
                12.sizeBoxH,
                GetBuilder<CartoonSubSectionLogic>(
                  init: logic,
                  id: 'vote',
                  builder: (controller) => Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Expanded(
                        flex: section.disVoteCount ?? 0,
                        child: _buildColorLine(Color(0xFFFF001F)),
                      ),
                      10.sizeBoxW,
                      Expanded(
                        flex: section.voteCount ?? 0,
                        child: _buildColorLine(Color(0xFF1169FF)),
                      ),
                    ],
                  ),
                ),
                12.sizeBoxH,
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    _builPKAction(
                      section,
                      logic,
                      title: '贫乳!!',
                      icon: 'haose_boob_small.png'.acgImgPath,
                      color: Color(0xFFFF001F),
                      type: 2,
                    ),
                    Spacer(),
                    Image.asset('haose_boob_pk.png'.acgImgPath, width: 125, height: 34),
                    Spacer(),
                    _builPKAction(
                      section,
                      logic,
                      title: '巨乳!!',
                      icon: 'haose_boob_big.png'.acgImgPath,
                      color: Color(0xFF3675DF),
                      type: 1,
                    ),
                  ],
                ),
                6.sizeBoxH,
              ],
            ),
          )
        ],
      ),
    );
  }

  _buildColorLine(Color color) {
    return Container(
      alignment: Alignment.center,
      height: 10,
      decoration: ShapeDecoration(
        color: color,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
      ),
    );
  }

  _builPKAction(
    AllSection section,
    CartoonSubSectionLogic logic, {
    String title = '',
    Color color = Colors.blueAccent,
    String icon = '',
    int type = 0,
  }) {
    return GestureDetector(
      child: Container(
        width: 101,
        height: 34,
        decoration: ShapeDecoration(
          color: color,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        ),
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(icon, width: 18, height: 18),
            12.sizeBoxW,
            Text(
              title,
              style: TextStyle(
                color: Colors.white,
                fontSize: 14,
                fontWeight: FontWeight.w400,
              ),
            )
          ],
        ),
      ),
      onTap: () => onVoute(section, type, logic),
    );
  }

  _buildPkText(String title) {
    return Text(
      title,
      style: TextStyle(
        color: Color(0xFF333333),
        fontSize: 14,
        fontWeight: FontWeight.w400,
      ),
    );
  }

  List<CartoonMediaInfo> handelPkSource(List<CartoonMediaInfo> allMediaInfo) {
    List<CartoonMediaInfo> list1 = []; //奇数
    List<CartoonMediaInfo> list2 = []; //偶数
    List<CartoonMediaInfo> value = [];

    int half = (allMediaInfo.length / 2).ceil();
    list1 = allMediaInfo.sublist(0, half);
    list2 = allMediaInfo.sublist(half);
    for (var i = 0; i < list1.length; i++) {
      value.add(list1[i]);
      if (list2.length >= i + 1) {
        value.add(list2[i]);
      }
    }
    return value;
  }

  //动漫投票 1、支持大胸 2、支持贫胸
  onVoute(AllSection item, int status, CartoonSubSectionLogic logic) async {
    // final hasVote = await lightKV.getBool(item.sectionID ?? '') ?? false;
    // if (hasVote) {
    //   showToast('已经投过票了～');
    //   return;
    // }
    // final result = await VidService.voteSectionById(item.sectionID ?? '', status);
    // if (result) {
    //   showToast("投票成功");
    //   int disVC = ((item.disVoteCount ?? 0) + 1);
    //   int vC = (item.voteCount ?? 0) + 1;
    //   status == 2 ? item.disVoteCount = disVC : item.voteCount = vC;

    //   logic.update(['vote']);
    //   lightKV.setBool(item.sectionID ?? '', true);
    // } else {
    //   showToast("投票失败");
    // }
  }
}

//7 三竖屏
class ThreeV extends CartoonSectionBaseType {
  static ThreeV? _instance;
  double height = (Get.width - 30) / 2.5 * 216 / 133;
  ThreeV._internal();
  //工厂构造函数
  factory ThreeV() {
    if (_instance == null) {
      _instance = ThreeV._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    return SliverMainAxisGroup(
      slivers: [
        SliverToBoxAdapter(child: _buildSectionHeader(section)),
        SliverPadding(
          padding: const EdgeInsets.only(left: 16, right: 16, bottom: 12),
          sliver: SliverGrid(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 12,
              crossAxisSpacing: 5,
              childAspectRatio: 111 / 188,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                CartoonMediaInfo? meidiaInfo = section.allMediaInfo?[index];
                return AcgItemWidget(info: meidiaInfo, coverV: false);
              },
              childCount: section.allMediaInfo?.length ?? 0,
            ),
          ),
        ),
      ],
    );
  }
}

//8 三竖屏
class TwoH extends CartoonSectionBaseType {
  static TwoH? _instance;

  late double itemWidth = (Get.width - 30) / 2.5;
  late double itemheight = itemWidth / 132 * 218;
  TwoH._internal();
  //工厂构造函数
  factory TwoH() {
    if (_instance == null) {
      _instance = TwoH._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    return SliverMainAxisGroup(
      slivers: [
        SliverToBoxAdapter(child: _buildSectionHeader(section)),
        SliverToBoxAdapter(
          child: SizedBox(
            height: itemheight,
            child: ListView.separated(
              padding: EdgeInsets.symmetric(horizontal: 16),
              scrollDirection: Axis.horizontal,
              separatorBuilder: (context, index) => 7.sizeBoxW,
              itemCount: section.allMediaInfo?.length ?? 0,
              itemBuilder: (context, index) {
                CartoonMediaInfo? meidiaInfo = section.allMediaInfo?[index];
                return Container(
                  width: itemWidth,
                  height: itemheight,
                  child: AcgItemWidget(info: meidiaInfo, coverV: true),
                );
              },
            ),
          ),
        ),
      ],
    );
  }
}

//10 九宫格
class NineGrid extends CartoonSectionBaseType {
  static NineGrid? _instance;
  double height = (Get.width - 30) / 2.5 * 216 / 133;
  NineGrid._internal();
  //工厂构造函数
  factory NineGrid() {
    if (_instance == null) {
      _instance = NineGrid._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    return SliverMainAxisGroup(
      slivers: [
        SliverToBoxAdapter(child: _buildSectionHeader(section)),
        SliverPadding(
          padding: const EdgeInsets.only(left: 16, right: 16, bottom: 12),
          sliver: SliverGrid(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 12,
              crossAxisSpacing: 6,
              childAspectRatio: 111 / 188,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                CartoonMediaInfo? meidiaInfo = section.allMediaInfo?[index];
                return AcgItemWidget(info: meidiaInfo);
              },
              childCount: section.allMediaInfo?.length ?? 0,
            ),
          ),
        ),
      ],
    );
  }
}

//8. 四宫格横
class FourSquareH extends CartoonSectionBaseType {
  static FourSquareH? _instance;

  FourSquareH._internal();
  //工厂构造函数
  factory FourSquareH() {
    if (_instance == null) {
      _instance = FourSquareH._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    return SliverMainAxisGroup(
      slivers: [
        SliverToBoxAdapter(child: _buildSectionHeader(section)),
        SliverPadding(
          padding: const EdgeInsets.only(left: 16, right: 16, bottom: 12),
          sliver: SliverGrid(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 12,
              crossAxisSpacing: 5,
              childAspectRatio: 111 / 190,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                CartoonMediaInfo? meidiaInfo = section.allMediaInfo?[index];
                return AcgItemWidget(info: meidiaInfo);
              },
              childCount: section.allMediaInfo?.length ?? 0,
            ),
          ),
        ),
      ],
    );
  }
}

//4 8横
class ThreeVerticalGrid extends CartoonSectionBaseType {
  static ThreeVerticalGrid? _instance;
  double height = 228;

  ThreeVerticalGrid._internal();
  //工厂构造函数
  factory ThreeVerticalGrid() {
    if (_instance == null) {
      _instance = ThreeVerticalGrid._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    return SliverToBoxAdapter(
      child: Column(
        children: [
          _buildSectionHeader(section),
          SizedBox(
            height: height,
            child: GridView.builder(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 1,
                mainAxisSpacing: 5,
                crossAxisSpacing: 5,
                childAspectRatio: 228 / 132,
              ),
              itemCount: section.allMediaInfo?.length ?? 0,
              scrollDirection: Axis.horizontal,
              itemBuilder: (context, index) {
                CartoonMediaInfo? meidiaInfo = section.allMediaInfo?[index];
                return AcgItemWidget(info: meidiaInfo);
              },
            ),
          ),
          SizedBox(height: 18),
        ],
      ),
    );
  }
}

//小列表
class TwoVH extends CartoonSectionBaseType {
  static TwoVH? _instance;
  double height = (Get.width - 30) / 3.5 * 152 / 128;

  TwoVH._internal();
  //工厂构造函数
  factory TwoVH() {
    if (_instance == null) {
      _instance = TwoVH._internal();
    }
    return _instance!;
  }

  @override
  Widget renderType(AllSection section, CartoonSubSectionLogic logic) {
    return SliverToBoxAdapter(
      child: Column(
        children: [
          _buildSectionHeader(section),
          SizedBox(
            height: 228,
            child: GridView.builder(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: 12,
                crossAxisSpacing: 8,
                childAspectRatio: 111 / 272,
              ),
              itemCount: section.allMediaInfo?.length ?? 0,
              padding: const EdgeInsets.symmetric(horizontal: 10),
              scrollDirection: Axis.horizontal,
              itemBuilder: (context, index) {
                CartoonMediaInfo? meidiaInfo = section.allMediaInfo?[index];
                return _buildPopularItem(meidiaInfo);
              },
            ),
          ),
          6.sizeBoxH,
        ],
      ),
    );
  }

  _buildPopularItem(CartoonMediaInfo? info) {
    //跳转到动漫情页
    return InkWell(
      onTap: () => pushToCartoonPage(info),
      child: SizedBox(
        width: 256,
        height: 110,
        child: Row(
          children: [
            Stack(
              children: [
                AspectRatio(
                  aspectRatio: 82 / 110,
                  child: NetworkImageLoader(
                    imageUrl: info?.verticalCover ?? '',
                  ),
                ),
                if (info?.isAudiobooks == true)
                  Positioned(
                    left: 8,
                    top: 8,
                    height: 24,
                    width: 24,
                    child: Image.asset('voice_noval_icon.png'.videoPath),
                  )
              ],
            ),
            12.sizeBoxW,
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    info?.title ?? '',
                    style: TextStyle(fontSize: 12, color: Colors.white.withOpacity(.9)),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  4.sizeBoxH,
                  Text(
                    '${info?.episodeNumberStatus ?? ''} · ${info?.getUpdateString}',
                    textAlign: TextAlign.left,
                    style: TextStyle(
                        fontSize: 11,
                        color: info?.updateStatus == 1 ? Color(0xffEEC76B) : Colors.white.withOpacity(.45),
                        fontWeight: FontWeight.w400),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  if (info?.tagDetails?.isNotEmpty == true) ...[
                    4.sizeBoxH,
                    SizedBox(
                      height: 17,
                      child: ListView.builder(
                        itemCount: info?.tagDetails?.length ?? 0,
                        scrollDirection: Axis.horizontal,
                        itemBuilder: (context, index) {
                          String? tagName = info?.tagDetails?[index].name;
                          return Container(
                            width: 31,
                            height: 17,
                            margin: EdgeInsets.only(right: 4),
                            padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
                            decoration: ShapeDecoration(
                              shape: RoundedRectangleBorder(
                                side: BorderSide(width: 0.50, color: Color(0xFF00929B)),
                                borderRadius: BorderRadius.circular(32),
                              ),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Text(
                                  '$tagName',
                                  style: TextStyle(
                                    color: Color(0xFF00929B),
                                    fontSize: 11,
                                    fontWeight: FontWeight.w400,
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                      ),
                    ),
                  ],
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

//猜你喜欢列表
class PreferencerGrid extends StatefulWidget {
  bool? likeLoading = true;
  int? selectIndex;
  PreferencesModel? preferencesModel; //猜你喜欢
  List<CartoonMediaInfo>? guessMediaInfoList;
  Function(int index)? onChangeRecomendSort;
  Function()? loadData;
  Function(double dy)? onInitOffset;
  ScrollController? scl;

  PreferencerGrid({
    Key? key,
    this.likeLoading,
    this.preferencesModel,
    this.guessMediaInfoList,
    this.onChangeRecomendSort,
    this.loadData,
    this.onInitOffset,
    this.scl,
    this.selectIndex,
  });

  @override
  State<PreferencerGrid> createState() => PreferencrGrideState();
}

class PreferencrGrideState extends State<PreferencerGrid> {
  GlobalKey currentKey = GlobalKey();
  Size? scrollSize;
  double? offsetY;
  PreferencesModel? get preferencesModel => widget.preferencesModel;
  List<CartoonMediaInfo>? get guessMediaInfoList => widget.guessMediaInfoList;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      getViewPortSize();
      getExposureOffset();
    });
  }

  void getViewPortSize() {
    try {
      final RenderObject? box = context.findRenderObject();
      final RenderAbstractViewport? viewport = RenderAbstractViewport.of(box);
      if (viewport != null) {
        scrollSize = viewport.paintBounds.size;
      }
    } catch (e) {
      // debugLog(e);
    }
  }

  void getExposureOffset() {
    try {
      RenderObject? box = context.findRenderObject();
      RenderAbstractViewport? viewport = RenderAbstractViewport.of(box);
      if (viewport == null || box == null || !box.attached) {
        return;
      }
      // box 为当前 Item 的 RenderObject
      // alignment 为 0 的时候获得距离起点的相对偏移量
      // 为 1 的时候获得距离终点的相对偏移量。
      final RevealedOffset offsetRevealToTop = viewport.getOffsetToReveal(box, 0.0, rect: Rect.zero);
      // offsetY = offsetRevealToTop.offset;
      widget.onInitOffset?.call(offsetRevealToTop.offset);
    } catch (e) {
      // debugLog(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      key: currentKey,
      children: [
        Padding(
          padding: EdgeInsets.only(top: 18),
          child: Image.asset('guessu_like_bg.webp'.commonImgPath, width: Get.width),
        ),
        Column(
          children: [
            SizedBox(height: 40),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 2),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: List.generate(preferencesModel?.sortType?.length ?? 0, (index) {
                  SortType? type = preferencesModel?.sortType?[index];
                  return Row(
                    children: [
                      _buildTypeAction(
                        type?.key ?? '',
                        widget.selectIndex == type?.value,
                        type?.value,
                      ),
                      if (index < ((preferencesModel?.sortType?.length ?? 0) - 1)) ...[
                        _buildSpeLine(),
                      ]
                    ],
                  );
                }),
              ),
            ),
            _buildLikeContent(),
          ],
        )
      ],
    );
  }

  _buildLikeContent() {
    if (widget.likeLoading == true) {
      return Padding(
        padding: EdgeInsets.symmetric(vertical: 100),
        child: LoadingCenterWidget(),
      );
    } else {
      if (guessMediaInfoList?.isNotEmpty == true) {
        return GridView.builder(
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            mainAxisSpacing: 12,
            crossAxisSpacing: 5,
            childAspectRatio: 111 / 188,
          ),
          itemCount: widget.guessMediaInfoList?.length ?? 0,
          itemBuilder: (context, index) {
            CartoonMediaInfo? meidiaInfo = widget.guessMediaInfoList?[index];
            return AcgItemWidget(info: meidiaInfo);
          },
        );
      } else {
        return Padding(
          padding: EdgeInsets.symmetric(vertical: 100),
          child: CErrorWidget(retryOnTap: () => widget.loadData?.call),
        );
      }
    }
  }

  Widget _buildTypeAction(String? title, bool? select, int? index) {
    return GestureDetector(
      onTap: () => widget.onChangeRecomendSort?.call(index ?? 0),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
        child: Text(
          title ?? '',
          style: TextStyle(
            fontSize: 12,
            fontWeight: select == true ? FontWeight.w500 : FontWeight.w400,
            color: select == true ? AppColors.primaryTextColor : AppColors.subTextColor66,
          ),
        ),
      ),
    );
  }

  _buildSpeLine() {
    return Text('|', style: TextStyle(fontSize: 13, color: Colors.black.withOpacity(.3)));
  }
}
